<?php
if (! class_exists ( "stcontroller_1_1" )) {
	class stcontroller_1_1 {
		protected static $_instance = null;
		public $view = null;

		public $config = array ();
		public $layout = "default";
		public $actionName = "index";
		public $isAjax = 0;
                public $pluginPage = "index";
                public $option = "";
                public $views = array();

		public function __construct($config) {
                        $this->setConfig($config);                       
                        $this->actionName = $config['current_action'];
			$this->layout = $this->config ['default_layout'];
			$this->isAjax = false;
			$this->view = new stview_1_1 ();
			$this->view->config = $this->config;                        
                        $this->option = get_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings');
		}

		public function __destruct() {

		}

		public function add_admin() {                    
                    if(is_admin ()){
                        $this->execute ();
                    }else{
                        if(isset($_REQUEST['page'])){
                            if($_REQUEST['page'] == $this->config['plugin_name']){
                                $this->execute ();
                            }
                        }else{
                            $this->execute ();
                        }
                    }                    
		}

		public function ajax_action() {
			$this->isAjax = true;
			$this->execute ();
			die ();
		}

		public static function getInstance() {
			if (null === self::$_instance) {
				self::$_instance = new self ();
			}
			return self::$_instance;
		}

		public function setConfig($config) {
			$this->config = $config;
			if ($this->actionName == "index") {
				$this->actionName = $config ['default_action'];
			}
			$this->config ['pluginDir'] = WP_PLUGIN_DIR . '/' . $config ['plugin_name'] . '/';
			$this->config ['backendCss'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/css/backend/';
			$this->config ['backendScript'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/scripts/backend/';
			$this->config ['frontendCss'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/css/frontend/';
			$this->config ['frontendScript'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/scripts/frontend/';
			$this->config ['imagesUrl'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/images/';
		}

		public function execute() {
                        if( is_admin() || in_array($this->actionName, array_keys($this->views))){
                            if (is_callable ( array ($this, $this->actionName ) ) == false) {
                                    die ( "<br />Action not found: <b>Class: " . $this->config ['plugin_name'] . "Controller, Action: " . $this->actionName . "</b> in " . __FILE__ );
                            }

                            $this->registerTabMenu ();

                            $actionNameCall = $this->actionName;
                            $this->$actionNameCall ();

                            $data = $this->view->getData ();
                            $data ['current_action'] = $this->actionName;
                            $output = get_include_contents ( $this->config ['pluginDir'] . "/views/{$this->actionName}.php", $data );

                            if ($this->isAjax) {
                                    echo $output;
                            } else {
                                $data = $this->view->getData ();
                                $data ['content'] = $output;
                                $data ['config'] = $this->config;
                                $data ['tabmenus'] = $this->tabMenu;
                                $data ['current_action'] = $this->actionName;
                                $data ['option'] = $this->option;
                                if(is_admin ()){
                                    $layout = get_include_contents ( $this->config ['pluginDir'] . "/views/layout/{$this->layout}.php", $data );
                                    echo $layout;
                                }else{
                                    $this->layout = $this->views[$this->actionName];
                                    if(empty($this->layout)) $this->layout = $this->config['default_theme_layout'];
                                    $layout = get_include_contents($this->config['pluginDir'] . "/views/layout/{$this->layout}.php",$data);
                                    echo $layout;
                                    exit;
                                }
                            }
                        }
		}

		public function head() {
                    $method = array($this, 'loadSourceAdmin' );
                    add_action('admin_head', $method);
		}

                public function loadCss(){
                    //this is function import javascript
                    echo '<link href="' . $this->config ['frontendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<link href="' . $this->config ['frontendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
                    ;
                }

                public function loadScript(){
                    //this is function import javascript
                    wp_enqueue_script('jquery');
                    wp_enqueue_script('validate', $this->config ['frontendScript'].'jquery.validate.pack.js', array( 'jquery' ) );
                    wp_enqueue_script('stcore', $this->config ['frontendScript'].'stcore.js');

                }

                public function loadSourceAdmin(){
                    //this is function import javascript
                    echo '<link href="' . $this->config ['backendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<link href="' . $this->config ['backendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.validate.pack.js"></script>';
                    echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stcore.js"></script>';
                    echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'ajaxupload.js"></script>';

                }

		public function customHead() {
                    $this->customAdminEnqueueScript();
                    $method = array($this, 'loadAdminCss' );
                    add_action('admin_head', $method);
                    $method = array($this, 'loadAdminScript');
                    add_action("admin_head", $method);
                }

                public function customAdminEnqueueScript() {}

                public function loadAdminCss(){}

                public function loadAdminScript(){}

		public function loadmodel($modelName) {
			$className = $modelName . "_model";
			$fileName = $this->config ['pluginDir'] . "models/{$modelName}.php";
			require_once $fileName;
			$obj = new $className($this->config);
			return $obj;
		}

		public function index() {}

		protected function addMenuPage($capability = '8', $icon = '') {
                    if($icon == ''){
                        $icon = $this->config['imagesUrl'].'slope-icon.png';
                    }
                    $method = array ($this, 'execute' );
                    $this->pluginPage = add_menu_page ( $this->config ['page_title'], $this->config ['plugin_menu_title'], $capability, $this->config ['plugin_name'], $method, $icon );

                    // load only script and css for this plugin
                    $method = array($this, 'head' );
                    add_action( "admin_print_footer_scripts-$this->pluginPage", $method );
                    $method = array($this, 'customHead' );
                    add_action( "admin_print_footer_scripts-$this->pluginPage", $method );
		}

		protected function setTabMenu($tabmenus) {
			foreach ( $tabmenus as $key => $value ) {
                            if(count($value) > 1){
                                foreach ( $value as $key_child => $value_child ) {
                                    $this->tabMenu [$key][$key_child] = $value_child;
                                }
                            }else
				$this->tabMenu [$key] = $value;
			}

		}

		protected function registerTabMenu() {
			if(isset($this->config['admin_tabs'])) {
				$this->setTabMenu ( $this->config['admin_tabs'] );
			}
		}

                public function activationPlugin() {}

                public function deactivationPlugin() {}

                public function getAction($action = '', $agrs = ''){
                    if($action != '' && !is_object($action)){
                        $actionNameCall = $action;
                    }
                    else{
                        $actionNameCall = $this->actionName;
                    }
                    if($agrs != '' )
                        $this->$actionNameCall ($agrs);
                    else
                        $this->$actionNameCall ();
                    $data = $this->view->getData();
                    $data ['current_action'] = $actionNameCall;
                    $output = get_include_contents ( $this->config ['pluginDir'] . "views/{$actionNameCall}.php", $data );

                    if($action != '' && !is_object($action)){
                        return $output;
                    }else{
                        echo $output;
                    }
                }

                protected function setView($views){
                    foreach ($views as $view => $layout) {
                        $this->views[$view] = $layout;
                    }
                }

                protected function registerView(){}

                protected function updateOption($data){
                    $option = get_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings');
                    foreach ($data as $key => $value) {
                        $option[$key] = $value;
                    }
                    update_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings', $option);
                }

                public function ajaxPostAction(){
                    $save_type = $_POST['type'];
                    //Uploads
                    if($save_type == 'upload'){
                        $clickedID = $_POST['data']; // Acts as the name
                        $filename = $_FILES[$clickedID];
                        $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                        $override['test_form'] = false;
                        $override['action'] = 'wp_handle_upload';
                        $uploaded_file = wp_handle_upload($filename, $override);
                        list($width, $height) = getimagesize($uploaded_file['file']);
                        if($_POST['thumbnail_width'] != ''){
                            $max_w = $_POST['thumbnail_width'];
                            $max_h = round(($max_w * $height) / $width);
                            if(isset($uploaded_file['file'])) {
                                    $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                                    $thumbnail_url = $upload_dir_url . basename($thumbnail);
                            }
                        }

                        if (!empty($uploaded_file['error'])) {
                            echo 'Upload Error: ' . $uploaded_file['error']."|*| Upload Error";
                        } else {
                            echo $uploaded_file['url']."|*|".$uploaded_file['file'];
                        } // Is the Response
                    } elseif ($save_type == 'image_remove') {
                        $file = $_POST['file']; // Acts as the name
                        $img_name = basename($file);                        
                        $img_name = explode('.', $img_name);
                        $img_name = $img_name[0];
                        $file_thumb = str_replace($img_name, $img_name.'-thumb', $file);
                        unlink ($file);
                        unlink ($file_thumb);
                    }
                }

	}
}
?>